package com.rd.config.security;

import com.rd.common.exception.UserLockException;
import com.rd.pojo.SysUser;
import com.rd.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 处理用户详细信息的认证和授权
 * 绑定自己sys_user表的用户进行登录
 */
@Slf4j
@Service
public class MyUserDetailServiceImpl  implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails = null;
        //1.从数据库中获取根据参数username查询出来的SysUser对象
        SysUser sysUser = sysUserService.getUserByName(username);
        log.info("从数据库获取到用户信息: {}",sysUser);
        try {
            if (Objects.isNull(sysUser)) {
                throw new UsernameNotFoundException("sys_user表中没有这个用户!");
            } else if ("1".equals(sysUser.getStatus())) {
                throw new UserLockException("该用户被封禁，不能登录");
            }else{
                //获取这个用户权限
                Long userId = sysUser.getId();
                List<GrantedAuthority> list = getUserAuthorityList(userId);
                //需要返回一个SpringSecurity的UserDetails对象
                // 参数1：用户名  参数2：密码(加密)  参数3：这个用户权限集合
                userDetails=new User(sysUser.getUsername(),
                        "{bcrypt}" + sysUser.getPassword(),list);

            }
        }catch (UserLockException exception){
            exception.printStackTrace();
        }
        return userDetails;
    }

    public List<GrantedAuthority> getUserAuthorityList(long userId){
        String str = sysUserService.getAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(str);
    }
}
